/*
 * TocFilesParser.java
 *
 *  created: 17.8.2012
 *  charset: UTF-8
 *  license: MIT (X11) (See LICENSE file for full license)
 */

package cz.mp.k3bg.core;

import cz.mp.k3bg.log.LoggerManager;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Logger;


/**
 * Získá seznam odkazů z Obsahu.
 * 
 * @author Martin Pokorný
 * @version 0.1
 */
public class TocFilesParser {

    // TODO DEBUG
    private static final boolean DEBUG = true;
    private static final Logger logger =
            LoggerManager.getLogger(TocFilesParser.class, DEBUG);
        
    private HtmlFile toc;
    private File tocFile;
            
    /** Cesty k souborům použitým v obsahu. */
    private ArrayList<String> filePaths = new ArrayList<String>();
    
    // -----
    
    /**
     * 
     * @param tocFile 
     * @throws IllegalArgumentException
     */
    public TocFilesParser(File tocFile) {
        this.tocFile = tocFile;
    }
    
    /**
     * 
     * @return
     * @throws IOException 
     */
    public ArrayList<String> parse() throws IOException {
        logger.fine("");
        initToc();
        
        parseRefs(toc.getReferences());
        
        return getFilePaths();
    }
    
    /**
     * 
     * @throws IOException 
     */
    private void initToc() throws IOException {
        toc = new HtmlFile(tocFile.getAbsolutePath());        
        toc.initIfFileExists();           
    }

    /**
     * 
     * @param allRefs 
     */
    private void parseRefs(ArrayList<Reference> allRefs) {
        String lastFilePath = "";
        for (Reference reference : allRefs) {
            String filePath = reference.getUrlWithoutParams();
            
            if (filePath.startsWith("http://") 
                    || filePath.startsWith("https://")
                    || filePath.startsWith("www.")) {
                continue;
            }
            
            if (! filePath.equals(lastFilePath)) {
                filePaths.add(filePath);
                logger.fine("href file =  " + filePath);
            }
            
            lastFilePath = filePath;
        }
    }
    
    /**
     * 
     * @return 
     */
    public ArrayList<String> getFilePaths() {
        return new ArrayList<String>(filePaths);
    }
    
}   // TocFilesParser.java
